package com.ethan.springcloud.helloserviceclient;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.PingUrl;
import com.netflix.loadbalancer.Server;
import com.netflix.niws.loadbalancer.NIWSDiscoveryPing;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author daifei
 * @date 2019/7/4
 */
@Slf4j
public class MyRule extends AbstractLoadBalancerRule {


    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {

    }

    @Override
    public Server choose(Object key) {
        log.info("进入自定义负载均衡策略！");
        List<Server> servers = this.getLoadBalancer().getAllServers();
        Server server = null;
        if (CollectionUtils.isEmpty(servers)){
            log.error("shit,no server found!!!!");
            return null;
        }else {
            NIWSDiscoveryPing niwsDiscoveryPing = new NIWSDiscoveryPing();
            PingUrl pingUrl = new PingUrl();
            servers.stream().forEach(e ->{
                log.info("server :{},servier is alive:{}",e,e.isAlive());
                log.info("server :{},niwsDiscoveryPing servier is alive:{}",e,niwsDiscoveryPing.isAlive(e));
                log.info("server :{},pingUrl servier is alive:{}",e,pingUrl.isAlive(e));
            });
            server = servers.stream().filter(e -> e.isAlive()).findFirst().get();
            log.info("最终选择的服务提供者：{}",server);
            return server;
        }
    }
}
